//
//  AppDelegate.m
//  HSY
//
//  Created by 陈浩 on 2017/3/31.
//  Copyright © 2017年 金开门. All rights reserved.
//

#import "AppDelegate.h"
#import <UMMobClick/MobClick.h>
#import <AudioToolbox/AudioToolbox.h>
#import "HSYUploadGeTuiTokenRequest.h"
#import "HSYRootTabBarController.h"

#import "HSYBalanceViewController.h"
#import "HSYAuditSuccessViewController.h"
#import "HSYFillInformationViewController.h"
#import "HSYTipView.h"
#import "HSYSpeechManager.h"


#define kGtAppId           @"ygse2nnwTp6CkuW0o2kxS3"
#define kGtAppKey          @"44Ho1HGR5jAHmnLbcD2mb7"
#define kGtAppSecret       @"emmlYejirJ83Njkt5dcMS"
#define kGtMasterSecret    @"O1M2iE6dqI8lyBAsZwPRX1"

static SystemSoundID shake_sound_male_id = 0;

static BOOL kFromBackGroud = NO; //判断app是否从后台进入

static NSInteger kPaymentSuccess = 200; //收款成功
static NSInteger kAuditSuccess = 100;  //审核成功
static NSInteger kAuditFail = 101;  //审核成功

@interface AppDelegate ()

@end

@implementation AppDelegate


+ (AppDelegate *)delfaultDelegate{
    return (id)[UIApplication sharedApplication].delegate;
}

/**
 *设置友盟
 */
-(void)setupUM
{
    [UMConfigInstance setAppKey:@"586ca0f1677baa5ff50011f3"];
    [MobClick setAppVersion:XcodeAppVersion];
    [MobClick startWithConfigure:UMConfigInstance];
    
#if DEBUG
    [MobClick setLogEnabled:YES];
#endif
}

/**
 *设置个推
 */
-(void)setGeTui
{
    [GeTuiSdk startSdkWithAppId:kGtAppId appKey:kGtAppKey appSecret:kGtAppSecret delegate:self];
    // 注册 APNs
    [self registerRemoteNotification];
}


/** 注册 APNs */
- (void)registerRemoteNotification {
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
    //ios10注册推送通知
    {
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        center.delegate = self;
        [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionCarPlay) completionHandler:^(BOOL granted, NSError *_Nullable error) {
            if (!error) {
                NSLog(@"request authorization succeeded!");
            }
        }];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
    }
#else
    {
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_8_0
        //ios8以后注册推送通知
        UIUserNotificationType types = (UIUserNotificationTypeAlert | UIUserNotificationTypeSound | UIUserNotificationTypeBadge);
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
#else
        //ios8之前注册推送通知
        UIRemoteNotificationType apn_type = (UIRemoteNotificationType)(UIRemoteNotificationTypeAlert |
                                                                       UIRemoteNotificationTypeSound |
                                                                       UIRemoteNotificationTypeBadge);
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:apn_type];
        
#endif
    }
#endif
    
}

//设置rootViewController
- (void)setupRootViewController{
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    
    HSYRootTabBarController *vc = [HSYRootTabBarController new];
    self.window.backgroundColor = [UIColor whiteColor];
    self.window.rootViewController = vc;
    [self.window makeKeyAndVisible];
}

//点击通知信息进入，跳转到目标页面
- (void)loadTargetPageWithCode:(NSInteger)code{
    if (code == kPaymentSuccess) { //付款成功
        [self pushToBalance];
    }else if (code == kAuditSuccess) { //审核成功
        [self pushToAuditSuccess];
    }else if (code == kAuditFail) { //审核失败
        [self presentToFillInfomation];
    }
}

//查看余额
- (void)pushToBalance{
    HSYBalanceViewController *vc = [[HSYBalanceViewController alloc] init];
    vc.hidesBottomBarWhenPushed = YES;
    
    UINavigationController *nav = [self.window.rootViewController.childViewControllers firstObject];
    [nav pushViewController:vc animated:YES];
}

//资料审核成功
- (void)pushToAuditSuccess{
    HSYAuditSuccessViewController * vc = [[HSYAuditSuccessViewController alloc] init];
    vc.hidesBottomBarWhenPushed = YES;
    
    UINavigationController *nav = [self.window.rootViewController.childViewControllers firstObject];
    [nav pushViewController:vc animated:YES];
}

//审核失败，完善资料
- (void)presentToFillInfomation{
    HSYFillInformationViewController *vc = [[HSYFillInformationViewController alloc] init];
    
    HSYBaseNavigationController *nav = [HSYBaseNavigationController navigtationControllerWithRootViewController:vc];
    
    [self.window.rootViewController presentViewController:nav animated:YES completion:nil];
    
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    [self setGeTui]; //配置个推
    [self setupUM]; //配置友盟统计
    [[APPCenter defaultCenter] check]; //检测是否为线上版本
    [[APPCenter defaultCenter] tryLoginComplete:nil]; //尝试登录，获取用户新信息
    [[HSYUserCenter instatce] restoreUserModel]; //恢复用户信息
    
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent]; //白色状态栏
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    
    [self setupRootViewController]; //配置根视图控制器
    
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)[[NSBundle mainBundle] URLForResource:@"suc1.wav" withExtension:nil],&shake_sound_male_id); //设置系统音效
    
    if (launchOptions) { //点击推送通知进入
        NSDictionary *dict = [launchOptions[@"UIApplicationLaunchOptionsRemoteNotificationKey"][@"date"] mj_JSONObject];
        if (dict[@"resultCode"]) {
            NSInteger code = [dict[@"resultCode"] integerValue];
            [self loadTargetPageWithCode:code]; //跳转到目标界面

        }
    }
    return YES;
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    kFromBackGroud = YES;
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    kFromBackGroud = NO;
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

/** 远程通知注册成功委托 */
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSString *token = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    token = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    HSYLog(@"\n>>>[DeviceToken Success]:%@\n\n", token);
    
    // 向个推服务器注册deviceToken
    [GeTuiSdk registerDeviceToken:token];
}

- (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    /// Background Fetch 恢复SDK 运行
    [GeTuiSdk resume];
    completionHandler(UIBackgroundFetchResultNewData);
}



#pragma mark IOS10以前版本通知（iOS10以前）
/**
 在iOS 10 以前，为处理 APNs 通知点击事件，统计有效用户点击数
 @param application application
 @param userInfo userInfo
 @param completionHandler completionHandler
 */
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    // 将收到的APNs信息传给个推统计
    [GeTuiSdk handleRemoteNotification:userInfo];
    
    if (kFromBackGroud) {
        NSDictionary *dict = [userInfo[@"date"] mj_JSONObject]; //不理解为什么是date，难道是data？
        if (dict[@"resultCode"]) {
            NSInteger code = [dict[@"resultCode"] integerValue];
            [self loadTargetPageWithCode:code];

        }
    }
    
    completionHandler(UIBackgroundFetchResultNewData);
}

#pragma mark IOS10版本通知

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
//  iOS 10: App在前台获取到通知
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
    
    HSYLog(@"willPresentNotification：%@", notification.request.content.userInfo);
    
    // 根据APP需要，判断是否要提示用户Badge、Sound、Alert
    completionHandler(UNNotificationPresentationOptionBadge | UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert);
}

//  iOS 10: 点击通知进入App时触发，在该方法内统计有效用户点击数
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    
    HSYLog(@"didReceiveNotification：%@", response.notification.request.content.userInfo);
    
    // [ GTSdk ]：将收到的APNs信息传给个推统计
    [GeTuiSdk handleRemoteNotification:response.notification.request.content.userInfo];
    
    if (kFromBackGroud) {
        if (response.notification.request.content.userInfo[@"resultCode"] ) {
            NSInteger code = [response.notification.request.content.userInfo[@"resultCode"] integerValue];
            [self loadTargetPageWithCode:code];
        }
    }
    
    completionHandler();
}
#endif


#pragma mark 个推代理方法
/** SDK启动成功返回cid */
- (void)GeTuiSdkDidRegisterClient:(NSString *)clientId {
    //个推SDK已注册，返回clientId
    HSYLog(@"\n>>>[GeTuiSdk RegisterClient]:%@\n\n", clientId);
    
    HSYUploadGeTuiTokenRequest *task = [[HSYUploadGeTuiTokenRequest alloc] init];
    task.clientId = clientId;
    
    [HSYNetworkManager POST:task success:nil failure:nil];
}

/** SDK遇到错误回调 */
- (void)GeTuiSdkDidOccurError:(NSError *)error {
    //个推错误报告，集成步骤发生的任何错误都在这里通知，如果集成后，无法正常收到消息，查看这里的通知。
    HSYLog(@"\n>>>[GexinSdk error]:%@\n\n", [error localizedDescription]);
}


- (void)GeTuiSDkDidNotifySdkState:(SdkStatus)aStatus{
    HSYLog(@"SdkStatus :%d",aStatus);
}

#pragma mark 个推透传
/** SDK收到透传消息回调 */
/*
 当 SDK 在线时（即 App 在前台运行时）进行消息推送，该消息将直接通过个推通道发送给 App ，通常这种方式比通过APNs发送来得更及时更稳定；当 SDK 离线时（即停止 SDK 或 App 后台运行 或 App 停止状态时）进行消息推送，个推平台会给苹果 APNs 推送消息，同时保存个推通道的离线消息，当 SDK 重新上线后，个推平台会重新推送所有离线的消息。
 APP 可以通过[GeTuiSdkDelegate GeTuiSdkDidReceivePayloadData]回调方法获取透传消息，其中payloadData参数为透传消息数据，offLine参数则表明该条消息是否为离线消息。示例代码如下
 
 */
- (void)GeTuiSdkDidReceivePayloadData:(NSData *)payloadData andTaskId:(NSString *)taskId andMsgId:(NSString *)msgId andOffLine:(BOOL)offLine fromGtAppId:(NSString *)appId {
    //收到个推消息
    NSString *payloadMsg = nil;
    if (payloadData) {
        payloadMsg = [[NSString alloc] initWithBytes:payloadData.bytes length:payloadData.length encoding:NSUTF8StringEncoding];
    }
    
    
    NSString *msg = [NSString stringWithFormat:@"taskId=%@,messageId:%@,payloadMsg:%@%@",taskId,msgId, payloadMsg,offLine ? @"<离线消息>" : @""];
    
    NSDictionary *dict = [payloadMsg mj_JSONObject];
    
    if ([HSYUserCenter instatce].appAuUser.uid.length) {
        [[HSYUserCenter instatce] getBalanceSuccess:nil failure:nil];
    }
    
    if (!offLine) {
        if ([dict[@"resultCode"] integerValue] ==kPaymentSuccess) {
            
            BOOL NotTip = [APPCenter defaultCenter].paymentTone;
            
            if (!NotTip) { //提示音
                AudioServicesPlaySystemSound(shake_sound_male_id);
            }
            
            if ([HSYUserCenter instatce].appAuUser.uid.length) {
                [HSYUserCenter instatce].appBizShop.status = @"2" ;
                [[HSYUserCenter instatce] saveUserModelToDocuments];
                [self showTipView:dict[@"resultMessage"]];
            }
        }
    }
    
    if ([dict[@"resultCode"] integerValue] == kAuditSuccess) {
        
        if ([HSYUserCenter instatce].appAuUser.uid.length) {
            [HSYUserCenter instatce].appBizShop.status = @"1" ;
            [[HSYUserCenter instatce] saveUserModelToDocuments];
            
            if (!offLine) {
                [self showTipView:dict[@"resultMessage"]];
            }
        }
    }
    
    
    if ([dict[@"resultCode"] integerValue] == kAuditFail) {
        if ([HSYUserCenter instatce].appAuUser.uid.length) {
            [HSYUserCenter instatce].appBizShop.status = @"3" ;
            [HSYUserCenter instatce].appAuUser.auStep = 0;
            [[HSYUserCenter instatce] saveUserModelToDocuments];
            
            if (!offLine) {
                alert_alam_tag(@"提示", @"您的审核信息被拒，是否开始审核", 100, @"取消", @"确定");
                return ;
            }
        }
    }
    
    HSYLog(@"\n>>>[GexinSdk ReceivePayload]:%@\n\n", msg);
}

-(void)showTipView:(NSString *)Message
{
    AudioServicesPlaySystemSound(1007);
//    [[UIApplication sharedApplication] setStatusBarHidden:YES];
    
//    UILabel *tipLable = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width - 40, 50)];
//    UIView *vi= [[UIView alloc] initWithFrame:CGRectMake(10, 20, [UIScreen mainScreen].bounds.size.width-20, 50)];
//    tipLable.backgroundColor = [UIColor clearColor];
//    tipLable.text = Message;
//    tipLable.center = CGPointMake(([UIScreen mainScreen].bounds.size.width-20)/2, 25);
//    tipLable.font = [UIFont systemFontOfSize:12.0];
//    vi.backgroundColor = [UIColor colorWithWhite:0.9 alpha:1];
//    [vi addSubview:tipLable];
//    
//    [self.window.rootViewController.view addSubview:vi];
//    
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3ull * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        [vi removeFromSuperview];
//        [[UIApplication sharedApplication] setStatusBarHidden:NO];
//    });
    
    HSYTipView *view = [[[NSBundle mainBundle] loadNibNamed:@"HSYTipView" owner:nil options:nil] firstObject];
    view.textLabel.text = Message;
    view.frame = CGRectMake(10, 20, [UIScreen mainScreen].bounds.size.width-20, 90);
    
    [view sizeThatFits:CGSizeMake(CGRectGetWidth(view.frame), 150)];
    
    [self showTipView:view hidenDelay:3];
}


- (void)showTipView:(UIView *)view hidenDelay:(CGFloat)delay{
    CGFloat height = view.frame.size.height;
    view.frame = CGRectMake(10, -height, [UIScreen mainScreen].bounds.size.width-20, height);
    [self.window addSubview:view];
    
    [UIView animateWithDuration:0.5 animations:^{
        view.frame = CGRectMake(10, 20, [UIScreen mainScreen].bounds.size.width-20, height);
    }];
    
    [UIView animateWithDuration:0.5 delay:delay + 0.5 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        view.frame = CGRectMake(10, -90, [UIScreen mainScreen].bounds.size.width-20, height);
    } completion:^(BOOL finished) {
        [view removeFromSuperview];
    }];
}


#pragma mark - UIUIAlertViewDelegate -
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (alertView.tag == 100) {
        [self presentToFillInfomation];
    }
}





@end
